#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstring>
using std::cout;
using std::endl;

void Usage(const char *arg)
{
    cout << "USAGE:" << endl;
    cout << "#         please enter:  " << arg << "serverip serverport" << endl;
}
// ./client 127.0.0.1 8888
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string ip(argv[1]);
    uint16_t port = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        cout << "socket err" << endl;
        exit(1);
    }
    cout << "socket success" << endl;
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = INADDR_ANY;

    int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        cout << "connect err" << endl;
        exit(1);
    }
    cout << "connect success" << endl;
    while (true)
    {
        cout << "please enter#";
        std::string what;
        std::getline(std::cin, what);
        send(sockfd, what.c_str(), what.size(), 0);
        char buffer[1024];
        int num = recv(sockfd, buffer, sizeof(buffer), 0);
        if (num > 0)
        {
            buffer[num] = 0;
            cout << buffer << endl;
        }
        else if (num < 0)
        {
            cout << "recv error" << endl;
            continue;
        }
    }
    return 0;
}